﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace CompositionPlugin.Service.Primitives
{
    internal class AsyncContext : IAsyncResult, IDisposable
    {
        public AsyncContext(ManualResetEvent waitHandle)
        {
            if (waitHandle == null)
                throw new ArgumentNullException("waitHandle");
            this.AsyncWaitHandle = waitHandle;
        }

        ~AsyncContext()
        {
            this.Dispose();
        }

        public object AsyncState { get; internal set; }

        public WaitHandle AsyncWaitHandle { get; private set; }

        public bool CompletedSynchronously { get; internal set; }

        public bool IsCompleted { get; internal set; }

        internal Delegate Action { get; set; }

        internal object Parameters { get; set; }

        internal AsyncCallback Callback { get; set; }

        internal Exception Error { get; set; }

        internal object Result { get; set; }

        internal void SetEvent()
        {
            (this.AsyncWaitHandle as ManualResetEvent).Set();
        }

        public void Dispose()
        {
            if (Interlocked.CompareExchange(ref this._disposed, 1, 0) == 0)
            {
                this.AsyncWaitHandle.Dispose();
            }
        }

        #region private

        private int _disposed = 0;

        #endregion
    }
}
